﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.CodeDom;
using NHibernate.Cfg.MappingSchema;
using MVCGen.Mappings;
using MVCGen.Generators.Entity;

namespace MVCGen.Generators {
	public static class StringExtensions {
		public static String MakeFieldName(this String s) {
			s = s.Substring(0, 1).ToLower() + s.Substring(1);
			return s;
		}
	}

	public class EntityGenerator {
		public List<CodeTypeDeclaration> Generate(HbmMapping input) {
			List<CodeTypeDeclaration> result = new List<CodeTypeDeclaration>();
			foreach(HbmClass entity in MappingHelper.ExtractClasses(input)) {
			    CodeTypeDeclaration item = new CodeTypeDeclaration();
				item.Name = entity.name;
				item.Members.Add(new HbmIdToFieldGenerator(entity.Id).Generate());
				item.Members.Add(new HbmIdToPropertyGenerator(entity.Id).Generate());

				foreach (Object part in entity.Items) {
					if (part is HbmProperty) {
						item.Members.Add(new HbmPropertyFieldGenerator(part as HbmProperty).Generate());
						item.Members.Add(new HbmPropertyPropertyGenerator(part as HbmProperty).Generate());
					} else if (part is HbmManyToOne) {
						item.Members.Add(new HbmManyToOneFieldGenerator(part as HbmManyToOne).Generate());
						item.Members.Add(new HbmManyToOnePropertyGenerator(part as HbmManyToOne).Generate());
					} else if (part is HbmBag) {
						item.Members.Add(new HbmBagFieldGenerator(part as HbmBag).Generate());
						item.Members.Add(new HbmBagPropertyGenerator(part as HbmBag).Generate());
					} else if (part is HbmSet) {
						item.Members.Add(new HbmSetFieldGenerator(part as HbmSet).Generate());
						item.Members.Add(new HbmSetPropertyGenerator(part as HbmSet).Generate());
					} else if (part is HbmMap) {
						item.Members.Add(new HbmMapFieldGenerator(part as HbmMap).Generate());
						item.Members.Add(new HbmMapPropertyGenerator(part as HbmMap).Generate());
					} else if (part is HbmList) {
						item.Members.Add(new HbmListFieldGenerator(part as HbmList).Generate());
						item.Members.Add(new HbmListPropertyGenerator(part as HbmList).Generate());
					} else if (part is HbmArray) {
						item.Members.Add(new HbmArrayFieldGenerator(part as HbmArray).Generate());
						item.Members.Add(new HbmArrayPropertyGenerator(part as HbmArray).Generate());
					}
				}
				result.Add(item);
			}

			return result;
		}
	}
}
